$(function() {

    lay('#version').html('-v' + laydate.v);
    laydate.render({
        elem: '#bg_time'
    });
    laydate.render({
        elem: '#ed_time'
    });

    var is_modify = false;

    $(".scs-pt").hide();
    $('.button-prev').hide();
    var at_name, b_time, e_time, join_num, id;
    $(".next-pt").on("click", function() {
        at_name = $(".at_name").val();
        b_time = $(".b-time").val();
        e_time = $(".e-time").val();
        join_num = $(".join_num").val();
        if (at_name == "" || b_time == "" || e_time == "" || join_num == "") {
            layer.msg("请完善信息");
        } else if (at_name.length > 45) {
            layer.msg("名称不能超过45个字")
        } else if (join_num < 2 || join_num > 10) {
            layer.msg("请输入2~10人")
        } else if (b_time + ' 00:00:00' >= e_time + ' 23:59:59') {
            layer.msg("结束的时间需大于开始时间")
        } else {
            $(".li1").removeClass("active").addClass("done");
            $(".li2").addClass("active");
            $(".bar").css("width", "100%");
            $("#tab1").removeClass("active");
            $("#tab2").addClass("active");
            $(".next-pt").hide();
        }
    });
    $(".toadd").on("click", function() {
        $(".stepT_1").addClass("step-active");
        $(this).hide();
    });
    $(".stepT").on("click", function(e) {
        var e = e || event;
        var btn_name = e.target.classList[1];
        switch (btn_name) {
            // 搜索框
            case "gd-search":
                var search_cont = $(".search-cont").val();
                $('#searchL').empty();
                ajax("get", "/active/search-goods", { goods_name: search_cont }, function success(data) {
                    if (data.code == 200) {
                        $(".search-list").empty();
                        var searchL = document.getElementById("searchL");
                        var res = data.data.lists;
                        var strli = '';
                        var listIdx = '';
                        for (var i = 0; i < res.length; i++) {
                            strli += '<li class="li xyb1" data-id="' + res[i].id + '">' + res[i].goods_name + '</li>';
                        }
                        searchL.innerHTML = strli;
                        for (var j = 0; j < data.data.count.total_page; j++) {
                            listIdx += idxHtml(j + 1)
                        }
                        $('.list_idx').html('').append(listIdx)
                        $('.list_idx').find('i').eq(data.data.count.current - 1).addClass('active');
                        xybClick();
                        togglePage(search_cont)

                        // $(".xyb1").unbind('click').on("click", function() {
                        //     $(".stepT_2").addClass("step-active").siblings().removeClass("step-active");
                        //     id = $(this).attr("data-id");
                        //     var T_body = document.getElementById("sku_tbody");
                        //     $("#sku_tbody").empty();
                        //     ajax("post", "/active/getsku", { id: id },
                        //         function success(data) {
                        //             if (data.code == 200) {
                        //                 console.log(data)
                        //                 var len = data.data.goods_attr.length;
                        //                 var is_isset = "false";
                        //                 var newArr = data.data.goods_attr;
                        //                 var cdn = data.data.cdn;
                        //                 for (var i = 0; i < len; i++) {
                        //                     var str = '<tr><td><input type="checkbox" class="inputc child_ck" attr_value="' + newArr[i].attr_name + ':' + newArr[i].attr_value + '" attr_img="' + newArr[i].attr_img + '" original_price="' + newArr[i].original_price + '" discount_price="' + newArr[i].discount_price + '" inventory="' + newArr[i].inventory + '" goods_attr_id="' + newArr[i].id + '"></td>'
                        //                     str += '<td>' + newArr[i].attr_value + '</td>'
                        //                     str += '<td ><img src="' + cdn + newArr[i].attr_img + '"/></td>'
                        //                     str += '<td>' + newArr[i].original_price + '</td>'
                        //                     str += '<td>' + newArr[i].discount_price + '</td>'
                        //                     str += '<td>' + newArr[i].inventory + '</td></tr>'
                        //                     var Tr = document.createElement("tr");

                        //                     Tr.innerHTML = str;
                        //                     T_body.appendChild(Tr)
                        //                 }
                        //                 $('.cnds').val(cdn);
                        //             }
                        //         }
                        //     );
                        // })
                    }
                });
                break;
                // 弹框2的全选
            case "total":
                var status = $(".checkbox").attr("status");
                $(".checkbox").parents(".stepT_2").find("input[type='checkbox']").prop("checked", status == "off" ? true : false);
                $(".checkbox").attr("status", status == "off" ? "on" : "off");
                break;
                // 不是全选
            case "child_ck":
                $(".total").prop("checked", false);
                break;
                // 弹框2的下一步
            case "xyb2":
                $(".stepT_3").addClass("step-active").siblings().removeClass("step-active");
                var is_checked = $("tbody input[type='checkbox']:checked");
                var cndsss = $(".cnds").val();
                var len = is_checked.length;
                var Th_tbody = document.getElementById("Th_tbody");
                $("#Th_tbody").empty();
                for (var i = 0; i < len; i++) {
                    var attr_value = $("tbody input[type='checkbox']:checked").eq(i).attr("attr_value");
                    var attr_img = $("tbody input[type='checkbox']:checked").eq(i).attr("attr_img");
                    var original_price = $("tbody input[type='checkbox']:checked").eq(i).attr("original_price");
                    var one_price = $("tbody input[type='checkbox']:checked").eq(i).attr("one_price");
                    var discount_price = $("tbody input[type='checkbox']:checked").eq(i).attr("discount_price");
                    var inventory = $("tbody input[type='checkbox']:checked").eq(i).attr("inventory");
                    var attribute_value_id = $("tbody input[type='checkbox']:checked").eq(i).attr("attribute_value_id");
                    var attr_id = $("tbody input[type='checkbox']:checked").eq(i).attr("id");

                    var str1 = '<td><input type="text" class="no_width deep" value="' + attr_value + '" disabled></td>'
                    str1 += '<td><input type="hidden" class="no_width deep" value="' + attr_img + '"><img src="' + cndsss + attr_img + '"/></td>'
                    str1 += '<td><input type="text" class="no_width shallow" value="' + discount_price + '" placeholder="请输入单购价"></td>'
                    str1 += '<td><input type="text" class="no_width shallow" value="' + one_price + '"></td>'
                    str1 += '<td><input type="text" class="no_width shallow" value="' + original_price + '"></td>'
                    str1 += '<td><input type="text" class="no_width shallow" value="' + inventory + '"></td>'
                    str1 += '<td style="display: none"><input type="hidden" value="' + attribute_value_id + '"></td>'
                    str1 += '<td style="display: none"><input type="hidden" value="' + attr_id + '"></td>'

                    var Tr = document.createElement("tr");
                    Tr.innerHTML = str1;
                    Th_tbody.appendChild(Tr)
                }
                break;
                //弹框2的上一步
            case "syb2":
                $(".stepT_1").addClass("step-active").siblings().removeClass("step-active");
                break;
                //弹框3的上一步
            case "syb3":
                $(".stepT_2").addClass("step-active").siblings().removeClass("step-active");
                break;
                //弹框3的确认
            case "qd":
                save();
                is_modify = false;
                break;
                //编辑
            case "edit":
                $(".stepT_3").addClass("step-active").siblings().removeClass("step-active");
                $(".gd-info").hide();
                // $(".scs-pt").hide();
                $(".button-prev").hide();
                is_modify = true;
                break;

            default:
                break;
        }
    });
    $(".qrxyb").on("click", function() {
        $("#tab1").hide();
        $("#tab2").addClass("active");
        $(".gd-info").show();
        at_name = $(".at_name").val();
        b_time = $(".b-time").val();
        e_time = $(".e-time").val();
        join_num = $(".join_num").val();
        $('.button-prev').show();
        $('.qrxyb').hide();
    })
    $('.button-prev').on('click', function() {
        $("#tab1,.qrxyb").show();
        $(".gd-info").removeClass("step-active")
        $("#tab2").removeClass("active");
        $('.button-prev').hide();
    })
    // 完成
    $(".scs-pt").on("click", function() {
        if (is_modify) {
            layer.confirm('尚有信息未保存，是否保存？', {
                btn: ['保存', '直接退出'] //按钮
            }, function() {
                save();
                var len = $("#qrinfo tr").length;
                var tArray = new Array();
                for (var i = 0; i < len; i++) {
                    var gd_info = [];
                    for (var j = 0; j < 8; j++) {
                        gd_info.push($("#qrinfo tr").eq(i).find("input").eq(j).val());
                    }
                    tArray.push({ attr_img: gd_info[1], collage_price: gd_info[2], one_price: gd_info[3], original_price: gd_info[4], inventory: gd_info[5], attribute_value_id: gd_info[6], goods_attre_id: gd_info[7] });
                };
                ajax("post", "/active/add", { active_attr: tArray, goods_id: id, active_name: at_name, active_num: join_num, begin_time: b_time, end_time: e_time },
                    function success(data) {
                        if (data.code == 200) {
                            layer.msg(data.msg);
                            setTimeout(function(){
                                location.href="/active/index";
                            },1000)
                        } else {
                            layer.msg(data.msg);
                        }
                    }
                )
            }, function() {
                location.href = "/active/index";
            });
        } else {
            var len = $("#qrinfo tr").length;
            var tArray = new Array();
            for (var i = 0; i < len; i++) {
                var gd_info = [];
                for (var j = 0; j < 8; j++) {
                    gd_info.push($("#qrinfo tr").eq(i).find("input").eq(j).val());
                }
                tArray.push({ attr_img: gd_info[1], collage_price: gd_info[2], one_price: gd_info[3], original_price: gd_info[4], inventory: gd_info[5], attribute_value_id: gd_info[6], goods_attre_id: gd_info[7] });
            };
            ajax("post", "/active/add", { active_attr: tArray, goods_id: id, active_name: at_name, active_num: join_num, begin_time: b_time, end_time: e_time },
                function success(data) {
                    if (data.code == 200) {
                        layer.msg(data.msg);
                        setTimeout(function(){
                            location.href="/active/index";
                        },1000)
                    } else {
                        layer.msg(data.msg);
                    }
                }
            )
        }
    });

    xybClick()

    function xybClick() {
        $(".xyb1").unbind('click').on("click", function() {
            $(".stepT_2").addClass("step-active").siblings().removeClass("step-active");
            id = $(this).attr("data-id");
            var T_body = document.getElementById("sku_tbody");
            $("#sku_tbody").empty();
            ajax("post", "/active/getsku", { id: id },
                function success(data) {
                    if (data.code == 200) {
                        var dIv = "<table class=' table  table-striped table-bordered table-advance table-hover'>";
                        dIv += '<thead><tr>';
                        dIv += '<th><input type="checkbox" class="checkbox total" status="off"></th>';
                        $(data.data.goods_attr.thead).each(function(i, item) {
                            dIv += '<th>' + item + '</th>'
                        })
                        dIv += '<th>拼团价</th>';
                        dIv += '<th>单购价</th>';
                        dIv += '<th>原价</th>';
                        dIv += '<th>库存</th>';
                        dIv += '</tr></thead>';
                        dIv += '<tbody>';
                        $(data.data.goods_attr.tbody).each(function($key, item) {
                            dIv += '<tr><td><input type="checkbox" class="inputc child_ck" attr_value="' + item.attr_value + '"  original_price="' + item.original_price + '" discount_price="' + item.discount_price + '" one_price="' + item.one_price + '" attr_img="' + item.images + '"   inventory="' + item.inventory + '"  attribute_value_id="' + item.attribute_value_id + '" id="' + item.id + '"></td>'
                            $(item.val).each(function(j, itemm) {
                                dIv += '<td>' + itemm.value + '</td>'
                            })
                            dIv += '<td>' + item.discount_price + '</td>';
                            dIv += '<td>' + item.one_price + '</td>';
                            dIv += '<td>' + item.original_price + '</td>';
                            dIv += '<td>' + item.inventory + '</td>';
                            dIv += '</tr>'
                        })
                        dIv+='</tbady>'
                        dIv+='</table>'
                        $("#sku_tbody").append(dIv);
                    }
                }
            );
        })
    }

    // 选择商品分页
    proList(1, "") //初次加载列表
    function proList(p, goodsName) {
        ajax("get", "/active/search-goods", { p: p, goods_name: goodsName },
            function success(data) {
                if (data.code == 200) {
                    var data = data.data;
                    var list = data.lists;
                    var listStr = '';
                    var listIdx = '';
                    for (var i = 0; i < list.length; i++) {
                        listStr += listHtml(list[i].id, list[i].goods_name);
                    }
                    for (var j = 0; j < data.count.total_page; j++) {
                        listIdx += idxHtml(j + 1)
                    }
                    $('.stepT .search-list').html('').append(listStr)
                    $('.list_idx').html('').append(listIdx)
                    $('.list_idx').find('i').eq(p - 1).addClass('active');
                    xybClick();
                    togglePage(goodsName)
                }
            }
        )
    }

    function togglePage(goodsName) {
        $('.list_idx').find('i').unbind('click').click(function() {
            var p = $(this).text().trim();
            if ($(this).hasClass('active')) { return }
            proList(p, goodsName)
        })
    }

    function listHtml(id, name) {
        return '<li class="li xyb1" data-id="' + id + '">' + name + '</li>'
    }

    function idxHtml(i) {
        return '<i class="btn">' + i + '</i>'
    }

})

function save() {
    $(".gd-info").addClass("step-active").siblings().removeClass("step-active");
    $(".scs-pt").css("background", "#87bb33");
    var Qrinfo = document.getElementById("qrinfo");
    $("#qrinfo").empty();
    $(".scs-pt").show();
    $(".button-prev").show();
    $("#Th_tbody tr").each(function(i) {
        var Tr = document.createElement("tr");
        var str2 = "";
        var gd_value = [];
        $("#Th_tbody tr").eq(i).find("td").each(function(j) {
            gd_value.push($("#Th_tbody tr").eq(i).find("input").eq(j).val());
        });
        var cndsss = $(".cnds").val();
        str2 += '<td><input type="text" value="' + gd_value[0] + '" disabled="disabled"></td>'
        str2 += '<td><input type="hidden" value="' + gd_value[1] + '" disabled="disabled"><img src="' + cndsss + gd_value[1] + '"/></td>'
        str2 += '<td><input type="text" value="' + gd_value[2] + '" disabled="disabled"></td>'
        str2 += '<td><input type="text" value="' + gd_value[3] + '" disabled="disabled"></td>'
        str2 += '<td><input type="text" value="' + gd_value[4] + '" disabled="disabled"></td>'
        str2 += '<td><input type="text" value="' + gd_value[5] + '" disabled="disabled"></td>';
        str2 += '<td>0</td>';
        str2 += '<td style="display:none;"><input type="hidden" value="' + gd_value[6] + '" disabled="disabled"></td>'
        str2 += '<td style="display:none;"><input type="hidden" value="' + gd_value[7] + '" disabled="disabled"></td>'
        Tr.innerHTML = str2;
        Qrinfo.appendChild(Tr);
    });

    function jungleF() {
        var flag = true;
        $("#Th_tbody tr").each(function(m) {
            $("#Th_tbody tr").eq(m).find("td").each(function(n) {
                var jungleI = $("#Th_tbody tr").eq(m).find("input").eq(n).val();
                if (jungleI == "") {
                    return flag = false;
                }
            })
        })
    }
    // console.log(jungleF())
}